import 'package:flutter/cupertino.dart';
import 'package:rxdart/rxdart.dart';
import 'package:schoollifedemo/base/dio_network_util.dart';
import 'package:schoollifedemo/base/routers.dart';
import 'package:schoollifedemo/base/url_contract.dart';
import 'package:schoollifedemo/commonwidget/common_base_viewmodel.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class RegisterPageViewModel extends BaseViewModel {
  PublishSubject registerStateSubject = PublishSubject<CommonLoadingState>();

  // 跳转到隐私界面
  void goToPrivacyPage(BuildContext context) {
    getApplication().routerNavigateTo(context, RoutersPath.privacyPage);
  }

  // 返回登录页面
  void backToLoginPage(BuildContext context) {
    getApplication().getRouter()?.pop(context);
  }

  // 注册账号
  Future<bool?> registerAccount(
      {required String account, required String password}) async {
    registerStateSubject.add(CommonLoadingState.loading);
    final params = <String, dynamic>{};
    params['account'] = account;
    String? convertPassword = await _convertSHA256(password);
    if (convertPassword == null) {
      registerStateSubject.add(null);
      return null;
    }
    params['password'] = convertPassword;
    Map<String, dynamic>? json =
        await getNetworkUtil().postHttp(UrlContract.createUser, params: params);
    if (json == null) {
      registerStateSubject.add(null);
      return null;
    }
    final resp = CommonResponse.fromMap(json);
    if (resp.status == 0) {
      if (resp.trueOrFalse == true) {
        // 注册成功
        registerStateSubject.add(CommonLoadingState.successTypeTwo);
        return true;
      } else {
        // 注册失败
        registerStateSubject.add(CommonLoadingState.failure);
        return false;
      }
    } else {
      // 服务器错误
      registerStateSubject.add(null);
      return null;
    }
  }

  // 查询账号是否存在
  Future<bool?> checkUserIsSave({required String account}) async {
    final params = <String, dynamic>{};
    params['account'] = account;

    Map<String, dynamic>? json = await getNetworkUtil()
        .postHttp(UrlContract.queryUserExists, params: params);
    if (json == null) {
      return null;
    }
    final response = CommonResponse.fromMap(json);
    if (response.status == 0) {
      return response.trueOrFalse;
    }
    return null;
  }

  // 转换为SHA256
  Future<String?> _convertSHA256(String password) async {
    return await getChannelService()
        .getCommonChannelFunc()
        ?.convertSHA256(password);
  }
}
